package com.rising.online.bean;


import com.rising.online.service.CompilerService;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

public class DynamicCompilationExecutor implements Callable<Map<String, Object>> {
    private CompilerService compilerService;
    private CompilerBean compilerBean;

    public DynamicCompilationExecutor(CompilerService compilerService, CompilerBean compilerBean) {
        this.compilerService = compilerService;
        this.compilerBean = compilerBean;
    }

    @Override
    public Map<String, Object> call() throws Exception {
        boolean flag = compilerService.compile(compilerBean);
        StringBuffer stringBuffer = new StringBuffer();
        if (flag) {
            stringBuffer.append("编译成功\n");
            stringBuffer.append("编译时间：" + compilerBean.getCompilerTime() + "ms\n");
            try {
                compilerService.runMain(compilerBean);
                stringBuffer.append("运行时间：" + compilerBean.getRunTime() + "ms\n");
            } catch (Exception e) {
                stringBuffer.append("运行主方法异常：" + e.getMessage());
            }
            stringBuffer.append("代码执行结果：\n");
            stringBuffer.append("========================================\n" + compilerBean.getRunResult() + "========================================\n");
        } else {
            stringBuffer.append("编译失败：\n" + compilerBean.getCompilerMessage() + "\n");
        }
        Map<String, Object> rtnMap = new HashMap<>();
        rtnMap.put("result", stringBuffer.toString());
        return rtnMap;
    }
}
